#include "MyScript.h"

#include <QFile>
#include <QDebug>

MyScript::MyScript(QString _file)
    : scriptFile(_file)
{
    activity = openScript();
}

MyScript::~MyScript()
{

}

bool MyScript::openScript()
{
    bool ret =false;
    QFile file(scriptFile);
    if(file.open(QIODevice::ReadOnly))
    {
        QTextStream in(&file);
        in.setCodec("UTF-8");
        QString script = in.readAll();
        qDebug () << script;
        file.close();
        engine.evaluate(script,scriptFile);
        ret = true;
    }else{
        qDebug()<< QString("Script file: %1 open fail!").arg(scriptFile);
    }
    return ret;
}

QScriptValue MyScript::myFunc(QString _funcName,QScriptValueList args
    ,QString rarg,QScriptValue *rval)
{
    if(!activity){
        qDebug()<< QString("Script file: %1 is not open, engine is not load!").arg(scriptFile);
        return QScriptValue();
    }
    try{
        if(engine.canEvaluate(_funcName)){
//            QScriptValue func =  engine.evaluate(_funcName);
            QScriptValue global = engine.globalObject();
			if (engine.hasUncaughtException())  {  
                int line = engine.uncaughtExceptionLineNumber();
                qDebug() << "uncaught global exception at line" << line << ":" << global.toString();
				return QScriptValue();
			} 
            QScriptValue func = global.property(_funcName);
			if (engine.hasUncaughtException())  {  
                int line = engine.uncaughtExceptionLineNumber();
                qDebug() << "uncaught func exception at line" << line << ":" << func.toString();
				return QScriptValue();
            }
            QScriptValue result = func.call(QScriptValue(), args);
			if (engine.hasUncaughtException())  {  
                int line = engine.uncaughtExceptionLineNumber();
				qDebug() << "uncaught result exception at line" << line << ":" << result.toString(); 
				return QScriptValue();
			} 
            if(!rarg.isEmpty()){
//                *rval = engine.globalObject().property(rarg);
                *rval = global.property(rarg);
            }
            return result;
        }else{
            qDebug()<< QString("Script func: %1 is not exist!").arg(_funcName);
            return QScriptValue();
        }
    }catch(...){
        qDebug()<< QString("Script func: %1 is Exception!").arg(_funcName);
        return QScriptValue();
    }
}
